<?php
/*
 * 根据输入参数跳转controller
 */
class TbfControllerRunner {
    public static $enterPointApiName = '';
    //如果该变量是空,表示不限制前缀
    public static $controllerAllowPrefixList = array();
    static function getApiName(){
        $apiName = TbfInput::inStr("n");
        if (empty($apiName)){
            $apiName = self::$enterPointApiName;
        }
        return $apiName;
    }
    public static function run(){
        try {
            $apiName = self::getApiName();
            if (empty($apiName)){
                TbfError::client('404 1',404);
                return;
            }
            if (!self::isValidApiName($apiName)){
                TbfError::client('404 2',404);
                return;
            }
            if (!empty(self::$controllerAllowPrefixList)) {
                $hasFound = false;
                foreach (self::$controllerAllowPrefixList as $prefix) {
                    if (TbfString::HasPrefix($apiName, $prefix)) {
                        $hasFound = true;
                        break;
                    }
                }
                if (!$hasFound) {
                    //该前缀不允许访问
                    TbfError::client('404 3',404);
                    return;
                }
            }
            // Owxc.Admin.Login.LoginPage
            $apiNameList = explode('.',$apiName);
            $functionName = array_pop($apiNameList);
            $className = implode('\\',$apiNameList);
            if (!class_exists($className)){
                TbfError::client('404 4',404);
                return;
            }
            $reflectionClass = TbfReflect::getReflectionClass($className);
            if (!$reflectionClass->implementsInterface('TbfController')){
                //不是一个TbfController
                TbfError::client('404 5',404);
                return;
            }
            if (!method_exists($className,$functionName)){
                //方法不存在
                TbfError::client('404 6',404);
                return;
            }
            $className::$functionName();
        }catch (\TbfError\ClientErrorException $e){
            TbfProtocol::clientError($e->getMessage(),$e->http_code);
        }
    }

    private static function isValidApiName($name){
        if (!is_string($name)){
            return false;
        }
        $len=count($name);
        for($i=0;$i<$len;$i++){
            $ch=ord($name[$i]);
            if (!(
                ($ch>=ord('a') && $ch<=ord('z')) ||
                ($ch>=ord('A') && $ch<=ord('Z')) ||
                ($ch>=ord('0') && $ch<=ord('9')) ||
                $ch==ord('.')
            )
            ){
                return false;
            }
        }
        return true;
    }
} 
